package com.goodwilldd.myapp.services.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goodwilldd.myapp.entities.Person;
import com.goodwilldd.myapp.predicate.PersonPredicates;
import com.goodwilldd.myapp.repository.PersonRepository2;
import com.goodwilldd.myapp.services.PersonService2;

@Service
public class RepositoryPersonService2 implements PersonService2 {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RepositoryPersonService2.class);

	@Resource
	private PersonRepository2 personRepository;

	@Transactional(readOnly = true)
	@Override
	public List<Person> search(String searchTerm) {
		LOGGER.debug("Searching persons with search term: " + searchTerm);

		// Passes the specification created by PersonPredicates class to the
		// repository.
		Iterable<Person> persons = personRepository
				.findAll(PersonPredicates.lastNameIsLike(searchTerm));
		return constructList(persons);
	}

	private List<Person> constructList(Iterable<Person> persons) {
		List<Person> list = new ArrayList<Person>();
		for (Person person : persons) {
			list.add(person);
		}
		return list;
	}

	public void setPersonRepository(PersonRepository2 personRepositoryMock) {
		this.personRepository = personRepositoryMock;
	}

}
